<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" :placeholder="$locale('student.Enter')" clearable size="small"
                    prefix-icon="el-icon-search" style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :load="loadNode" lazy :props="defaultProps" :expand-on-click-node="false"
                   :filter-node-method="filterNode" ref="tree" node-key="id" highlight-current
                   @node-click="handleNodeClick" />
        </div>
      </el-col>
      <!--数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="120px">
          <el-form-item :label="$locale('jobList.add.Student Name')" prop="studentName">
            <el-input v-model="queryParams.studentName"
                      :placeholder="$locale('jobList.add.Please enter the student name')" clearable style="width: 240px"
                      @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="状态" clearable style="width: 240px">
              <el-option v-for="dict in dict.type.data_status" :key="dict.value" :label="dict.label"
                         :value="+dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$locale('student.Student email')" prop="contactEmail">
            <el-input v-model="queryParams.contactEmail"
                      :placeholder="$locale('student.Please enter the student email address')" clearable
                      style="width: 240px" @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
              {{ $locale('geWudevice.add.search for') }}
            </el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $locale('geWudevice.reset') }}
            </el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" size="mini" @click="handleFreeze()" :disabled="ids.length == 0">
              {{ $locale('school.add.Batch freeze') }}
            </el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="teacherList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column :label="$locale('student.student')" align="center" key="studentName" prop="studentName">
          </el-table-column>
          <el-table-column :label="$locale('jobList.add.email')" align="center" key="contactEmail" prop="contactEmail"
                           width="160">
          </el-table-column>
          <el-table-column :label="$locale('myClass.add.School Name')" align="center" key="schoolName"
                           prop="schoolName">
          </el-table-column>
          <el-table-column sortable column-key="status"
                           :filters="[{text: $locale('classList.normal'), value: '0'}, {text: $locale('classList.freeze'), value: '1'}]"
                           :filter-method="filterHandler" :label="$locale('geWudevice.add.state')" align="center"
                           key="status" prop="status">
            <template slot-scope="scope">
                            <span v-for="item in dict.type.data_status">
                                <el-tag v-if="item.value == scope.row.status"
                                        :type="scope.row.status == 0?'success':'danger'" effect="dark">
                                    {{ item.label }}
                                </el-tag>
                            </span>
            </template>
          </el-table-column>
          <el-table-column :label="$locale('student.Facial recognition frequency')" align="center" key="facialNum"
                           prop="facialNum">
          </el-table-column>
          <el-table-column :label="$locale('formMarkering.list.operate')" align="center" width="160"
                           class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="handleFreeze(scope.row)">
                {{ scope.row.status == 0 ? $locale('classList.freeze') : $locale('classList.thaw') }}
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleView(scope.row)">
                {{ $locale('geWudevice.view') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                    @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 添加 -->
    <teacherView ref="teacherView" @getList="getList"></teacherView>
    <viewDialog ref="view" />
  </div>
</template>

<script>
import { deleteById, list, setStatus, setStatusByIds } from '@/api/business/student';
import { getListByClassNameOrSchoolName } from '@/api/business/class';
import { schoolSelect } from '@/api/experiment/experimentList';
import teacherView from './add/index.vue';
import viewDialog from './add/view.vue';
import { getNames } from '@/utils/index';

export default {
  name: 'teacher',
  dicts: ['data_status'],
  components: { teacherView, viewDialog },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      teacherList: [],
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 表单参数
      defaultProps: {
        children: 'zones',
        isLeaf: 'leaf',
        label: 'name'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentName: '',
        status: '',
        contactEmail: ''
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      list(this.queryParams).then(({ data }) => {
        this.teacherList = data.records;
        this.total = data.total;
        this.loading = false;
      });
    },
    filterHandler(value, row, column) {
      const property = column['property'];
      return row[property] == value;
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      return new Promise((resolve, reject) => {
        schoolSelect().then(response => {
          let data = response.data.map(item => {
            item['name'] = item.schoolName;
            item['leaf'] = false;
            return item;
          });
          resolve(data);
        }).catch(error => {
          reject(error);
        });
      });
    },

    getDeptTreeClass(node) {
      return new Promise((resolve, reject) => {
        getListByClassNameOrSchoolName({ name: node.data.name }).then(response => {
          let data = response.data.map(item => {
            item['name'] = item.className;
            return item;
          });
          resolve(data);
        }).catch(error => {
          reject(error);
        });
      });
    },
    // 查看
    handleView(row) {
      this.$refs.view.show(row);
    },
    loadNode(node, resolve) {
      // 判断节点的层级，根据层级决定使用不同的接口加载数据
      if (node.level === 0) {
        // 第一层级节点使用接口1加载数据
        this.getDeptTree().then(data => {
          resolve(data);
        }).catch(error => {
          console.error('Failed to load data:', error);
          resolve([]);
        });
      } else if (node.level === 1) {
        // 第二层级节点使用接口2加载数据
        this.getDeptTreeClass(node).then(data => {
          resolve(data);
        }).catch(error => {
          console.error('Failed to load data:', error);
          resolve([]);
        });
      } else {
        // 其他层级的节点暂不处理，可以根据需要进行扩展
        resolve([]);
      }
    },
    /** 冻结按钮操作 */
    handleFreeze(row) {
      const Ids = row && row.id || this.ids;
      this.$modal.confirm(this.$locale
      ('geWudevice.tip4') + getNames(this.teacherList, Ids, 'studentName') + this.$locale('geWudevice.tip2')).then(() => {
        if (row && row.id) {
          setStatus({ id: Ids }).then(() => this.getList());
        } else {
          setStatusByIds({ id: Ids }).then(() => this.getList());
        }
      }).then((res) => {
        if (res.code == 200) this.$modal.msgSuccess(this.$locale('geWudevice.tip5'));
      }).catch(() => {
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.schoolName.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      if (data.className) {
        this.queryParams.classId = [data.id];
        this.handleQuery();
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.queryParams.classId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleBatch() {
      list({ id: this.ids }).then(({ data }) => {
        this.$modal.msgSuccess(this.$locale('jobList.Batch success'));
      });
    },
    /** 报价按钮操作 */
    handleQuotation(row) {
      this.$refs.teacherView.handleUpdate(row);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = row.id || this.ids;
      this.$modal.confirm(this.$locale('geWudevice.tip1') + getNames(this.deviceList, Ids, 'studentName') + this.$locale('geWudevice.tip2')).then(function() {
        return deleteById({ id: Ids });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$locale('geWudevice.tip3'));
      }).catch(() => {
      });

    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-table__row--level-1 .el-checkbox {
  display: none;
}
</style>
